package com.ld.admin.controller.system;

import java.util.List;
import java.util.Map;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ld.admin.controller.AdminBasicController;
import com.ld.common.plugin.Plugin;
import com.ld.common.plugin.PluginManager;
import com.ld.common.plugin.PluginUtil;
import com.ld.shieldsb.common.core.model.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * 插件管理
 * 
 * @ClassName SysPluginController
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年04月03日 11:17:54
 *
 */
@Api(tags = "插件管理")
@ConditionalOnProperty(prefix = "modules.sc.system", name = "plugin.enable", havingValue = "true", matchIfMissing = true)
@Controller(value = "systemSysPluginController")
@RequestMapping("${shieldsb.adminPath}/system/plugin")
public class SysPluginController extends AdminBasicController<Plugin> {

    @ApiOperation(value = "首页", notes = "")
    @RequestMapping(path = "", method = RequestMethod.GET)
    public String index() {
        List<Plugin> list = PluginManager.getPlugins();
        Map<String, String> loadInfos = PluginUtil.getPreferenceMapOrInit(list);
//        List<Map<String, String>> pluginList = new ArrayList<>();
//        list.forEach(plugin -> {
//            Map<String, String> map = new HashMap<>();
//            map.put("className", plugin.getClass().getName());
//            String clssSimpleName = plugin.getClass().getSimpleName();
//            String resource = plugin.getClass().getResource(clssSimpleName + ".class").getFile();
//            resource = StringUtils.substringBefore(resource, "!");
//            map.put("resourcePath", resource); // 资源路径，jar包路径或者class路径
//            map.put("simpleResourcePath", StringUtils.substringAfterLast(resource, "/")); // 资源路径，只保留jar包
//            pluginList.add(map);
//        });
        request.setAttribute("loadInfos", loadInfos);
//        request.setAttribute("list", pluginList);
        request.setAttribute("list", list);
        return "a/system/plugin/plugin_list";
    }

    @ApiOperation(value = "更新加载情况", notes = "")
    @RequestMapping(path = "updateLoad", method = RequestMethod.POST)
    // 返回json格式
    @ResponseBody
    public Object updateLoad() {
        String pluginName = getString("name");
        String load = getString("load");
        Result result = PluginUtil.savePreferences(pluginName, "1".equals(load) ? "true" : "false");
        return result;
    }

}